import os
import matplotlib.pyplot as plt


class TemporalCV:
    timestamp = 0
    locations = []

    def __init__(self, timestamp, locations):
        self.timestamp = timestamp
        self.locations = locations


class TemporalCVSeq:
    TemporalCV_list = []
    groud_truth = []

    def __init__(self, file_dir):
        in_file = open(file_dir + '\\cv_timestamp.txt', 'r')
        timestamps = []
        lines = in_file.readlines()
        for line in lines:
            datas = line.split(' ')
            timestamp = int(datas[1][:-1])
            timestamps.append(timestamp)
        in_file.close()

        length_cvseq = len(timestamps)
        for index in range(length_cvseq):
            print('index{0}'.format(index))
            filename = file_dir + '\\cv\\' + 'loc_{0}.txt'.format(index)
            if not os.path.exists(filename):
                continue
            in_file = open(filename, 'r')
            lines = in_file.readlines()
            length_lines = len(lines)
            locations = []
            for i in range(1, length_lines):
                datas = lines[i].split(' ')
                x = int(datas[0])
                z = 0

                if len(datas) == 2:
                    y = int(datas[1][:-1])
                else:
                    y = int(datas[1])
                    z = int(datas[2])

                locations.append((x, y))
                if z == 1:
                    self.groud_truth.append((x, y))
            self.TemporalCV_list.append(TemporalCV(timestamps[index], locations))

    def __str__(self):
        out_string = ''
        for TemporalCV in self.TemporalCV_list:
            out_string = out_string + '{}:\n'.format(TemporalCV.timestamp)
            for (x, y) in TemporalCV.locations:
                out_string = out_string + '{} {}\n'.format(x, y)
        return out_string

    def plot_out(self):
        for index, tem_cv in enumerate(self.TemporalCV_list):
            plt.clf()
            locations = tem_cv.locations
            x_list = []
            y_list = []
            for (x, y) in locations:
                x_list.append(x)
                y_list.append(y)
            plt.xlim(-1000, 2000)
            plt.ylim(-1000, 2000)
            plt.scatter(x_list, y_list)
            plt.savefig('tmp\\{}.png'.format(index))

    def ground_truth_seq(self, t):
        res = []
        for tem_cv in self.TemporalCV_list:
            (x, y) = tem_cv.locations[0]
            if tem_cv.timestamp >= t - 5000:
                res.append((x, y))
        return res







